//
//  BPHomePictureView.swift
//  BPWeiBo
//
//  Created by apple on 16/4/13.
//  Copyright © 2016年 apple. All rights reserved.

import UIKit
import SDWebImage
//cell的重用ID
let itemID = "item"
//设置图片之间的间距
private let pictureCellMargin:CGFloat = 3
//获取这个view的最大的宽度
private let maxViewWidth:CGFloat = (ScreenWidth - 2*StatusCellMargin)
//通过最大的宽度来获取每一个item最大的宽度
private let maxItemWidth:CGFloat = (maxViewWidth - 2*pictureCellMargin) / 3

class BPHomePictureView: UICollectionView {
    
    //定义一个BPPictureView类型的数组,当我们外界传入数据给这个数组的时候,这个视图就可以将视图显示出来并且返回给调用它的类去显示
    var pictureViewImg:[BPPictureView]? {
        didSet{
            //在这里面我们要根据传进来的图片的数量来设置view的size
            //获取视图的大小
            let picSize = setUpCollectionViewSize()
            //更新约束
            self.snp_updateConstraints { (make) -> Void in
                  make.size.equalTo(picSize)
            }
            //刷新数据
            self.reloadData()
        
        }
    }
    
    //MARK:定义一个方法,返回值是CGSize,判断传进来的图片是多少个,根据图片的数量来计算我们这个视图的大小
    //1.单张图片显示图片原比例尺寸
    //2.四张图片  2 * 2
    //3. 其他的张图片就按照 3 * n(根据图片数量来计算)
    private func setUpCollectionViewSize() -> CGSize {
        
        let imgUrls = pictureViewImg?.count ?? 0
        
        //1.当没有图片的时候就放回为0
        if imgUrls == 0 {
            return CGSizeZero
        }
        //2.当图片为一张的时候就显示为view的原来的尺寸
        //2.1获取到我们view的layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        if imgUrls == 1 {
            let itemSize1 = CGSizeMake(100, 150)
            layout.itemSize = itemSize1
            return itemSize1
        
        }
        
        
        //MARK:在这里设置每一个item的size
        layout.itemSize = CGSize(width: maxItemWidth, height: maxItemWidth)

        //3.当图片为4张得时候
        if imgUrls == 4 {
            
            let w = maxItemWidth * 2 + pictureCellMargin
            
            return CGSize(width: w, height: w)
            
        }
        //当程序走到这里,就一定是其他的多张图片
        //设置显示图片的行数
        let row = CGFloat ((imgUrls-1)/3 + 1)
        //获取view的高度
        let h = row * maxItemWidth + (row - 1) * pictureCellMargin
        
        return CGSize(width: maxViewWidth, height: h)
    }
    
    //初始化视图
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //定义一个layout
        let layout = UICollectionViewFlowLayout()
        //设置布局的item之间间距
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        super.init(frame: frame, collectionViewLayout: layout)
        backgroundColor = BapiColor//UIColor.blackColor()
        //设置数据源对象
        self.dataSource = self
        self.delegate = self
        //注册cell
        self.registerClass(BPPictureCell.self, forCellWithReuseIdentifier: itemID)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//MARK:conllectionView 的数据源方法
extension BPHomePictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
//    override func numberOfItemsInSection(section: Int) -> Int {
//        return 1
//    }

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureViewImg?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(itemID, forIndexPath: indexPath) as! BPPictureCell
        
        //cell.backgroundColor = randomColor()
        cell.picture = pictureViewImg![indexPath.item]
        return cell
    }
    
    //MARK:代理方法,选中这个cell的方法.当我们选中的时候让我们这个图片放大
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        /*
         创建SDPhotoBrowser实例
         
         SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
         
         browser.sourceImagesContainerView = 原图的父控件;
         
         browser.imageCount = 原图的数量;
         
         browser.currentImageIndex = 当前需要展示图片的index;
         
         browser.delegate = 代理;
         
         [browser show]; // 展示图片浏览器
         */
        
        let sdPhtotoBrowser = SDPhotoBrowser()
        sdPhtotoBrowser.sourceImagesContainerView = self
        sdPhtotoBrowser.imageCount = (pictureViewImg?.count)!
        sdPhtotoBrowser.currentImageIndex = indexPath.item
        sdPhtotoBrowser.delegate = self
        sdPhtotoBrowser.show()
    }

}

//MARK:SDPhotoBrowser的代理方法
extension BPHomePictureView: SDPhotoBrowserDelegate {
    //返回高清图的image对象
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        //1.先获取对应的indexpath
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        //2.在获取对应的图片
        let picture = pictureViewImg![indexPath.item]
        //3.将缩略图的URL转换成高清图的URL   original  bmiddle
        if let putongUrl = picture.thumbnail_pic?.stringByReplacingOccurrencesOfString("thumbnail", withString: "original") {
        let url = NSURL(string: putongUrl)
            return url
        }
        
        return nil
    }
    //返回缩略图的image对象
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        
        if let cell = self.cellForItemAtIndexPath(indexPath) as? BPPictureCell {
            
         return cell.iconImgView.image
            
        }
        
        return nil
    }
    
}
//定义一个cell类,在这里设置cell里面的数据
class BPPictureCell:UICollectionViewCell {
    
    //设置图片的属性
    var picture:BPPictureView? {
        didSet{
            let url = NSURL(string: picture?.thumbnail_pic ?? "")
            //let url = NSURL(string: picture?.original_pic ?? "")
            //let url = NSURL(string: picture?.bmiddle_pic ?? "")
            iconImgView.sd_setImageWithURL(url)
        }
    }
    
    //定义一个iconView的属性,懒加载视图
   private lazy var iconImgView: UIImageView = {
        let icon = UIImageView()
        //设置填充模式
        icon.contentMode = .ScaleAspectFill
        //手写代码需要手动设置裁剪
        icon.clipsToBounds = true
        
        return icon
        }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setIconUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置cell的UI
    private func setIconUI() {
        contentView.addSubview(iconImgView)
        
        //设置约束
        iconImgView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
    }

}
